package com.coder520.sync_learning.demo.httpServer;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.zip.InflaterInputStream;

import com.coder520.sync_learning.demo.threadPool.DefultThreadPool;
import com.coder520.sync_learning.demo.threadPool.ThreadPool;

public class SimpleHttpServer {
//	处理Httprequest的	线程池
	static ThreadPool<HttpRequestHandler> threadPool=new DefultThreadPool<HttpRequestHandler>(1);

	
//	SimpleHttpServer的根目录
	static String basePath;
	
	static ServerSocket serverSocket;
	
	static int port=8080;
	
	public SimpleHttpServer(int port) {
		if (port>0) {
			SimpleHttpServer.port=port;
		}
	}
	
	public static void setBasePath(String basePath) {
		if (basePath!=null&&new File(basePath).exists()&&new File(basePath).isDirectory()) {
			SimpleHttpServer.basePath = basePath;
		}
	}
	
	
	public static void start	() throws IOException {
		serverSocket=new ServerSocket(port);
		Socket socket=null;
		while((socket=serverSocket.accept())!=null) {
//			接受一个客户端socket，生成一个httprequesthandler,放入到线程池执行
			threadPool.execute(new HttpRequestHandler(socket));
		}
		
		serverSocket.close();
	}
	static class HttpRequestHandler implements Runnable{
		private Socket socket;
		
		public HttpRequestHandler(Socket socket) {
			// TODO Auto-generated constructor stub
			this.socket=socket;
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
				String line=null;
				BufferedReader br=null;
				BufferedReader reader=null;
				PrintWriter out=null;
				InputStream in=null;
				
				try {
					reader=new BufferedReader(new InputStreamReader(socket.getInputStream()));
					String header=reader.readLine();
					
//					由根路径计算出绝对路径
					String filePath=basePath+header.split(" ")[1];
					out =new PrintWriter(socket.getOutputStream());
					
//					如果请求的资源后缀为jpg护着ICO，那么便读取资源并且输出
					if (filePath.endsWith("jpg")||filePath.endsWith("ico")) {
						in=new FileInputStream(filePath);
						
						ByteArrayOutputStream baos=new ByteArrayOutputStream();
						int i=0;
						while ((i=in.read())!=-1) {
							baos.write(i);
						}
						
						byte[] arr=baos.toByteArray();
						
						out.println("HTTP/1.1 200 OK");
						out.println("Server: Molly");
		                out.println("Content-Type: image/jpeg");
		                out.println("Content-Length: " + arr.length);
		                out.println("");
		                socket.getOutputStream().write(arr,0,arr.length);
					}else {
						br=new BufferedReader(new InputStreamReader(new FileInputStream(filePath)));
						out=new PrintWriter(socket.getOutputStream());
						out.println("HTTP.1.1 200 OK");
						out.println("Server: Molly");
		                out.println("Content-Type:text/html;charset=UTF-8");
		                out.println("");
		                
		                while ((line=br.readLine())!=null) {
		                	out.println(line);
						}
					}
					
					out.flush();
				} catch (Exception e) {
					// TODO: handle exception
					out.println("HTTP/1.1 500");
					out.println("");
					out.flush();
				}finally {
					close(br,in,reader,out,socket);
				}
		}
		/**
		 * 关闭流或者socket
		 * @param br
		 * @param in
		 * @param reader
		 * @param out
		 * @param socket2
		 *	2018年6月12日
		 */
		private void close(Closeable... closeable) {
			// TODO Auto-generated method stub
			if (closeable!=null) {
				for (Closeable closeable2 : closeable) {
					try {
						closeable2.close();
					} catch (Exception e) {
						// TODO: handle exception
					}
				}
				
			}
		}
	}
}
